package com.example.rpcdemo.service;

import com.example.rpccommon.client.RpcClient;
import com.example.rpccommon.config.ServiceDiscovery;
import com.example.rpccommon.proxy.IAsyncObjectProxy;
import com.example.rpccommon.proxy.RPCFuture;
import com.example.rpccommon.entity.UserInfo;
import com.example.rpccommon.service.UserService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

@RestController
public class UserController {

    @Resource
    RpcClient rpcClient;

    @RequestMapping("/test")
    public Object test(String name) {
        // Sync call,核心是rpcFuture的get
        UserService userService = rpcClient.create(UserService.class);
        String result1 = userService.getAccessToken("World");
        // Async call
        IAsyncObjectProxy client = rpcClient.createAsync(UserService.class);
        RPCFuture userFuture = client.call("getUserInfo", "World");
        try {
            UserInfo result2 = (UserInfo) userFuture.get(3000, TimeUnit.MILLISECONDS);
            result2.setResult(result1);
            return result2;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        return "error";
    };
    //test
    public static void main(String[] args) throws Exception {
        final RpcClient rpcClient2 = new RpcClient("192.168.0.23:6666",new ServiceDiscovery("192.168.0.23:2181"));

        IAsyncObjectProxy client = rpcClient2.createAsync(UserService.class);
        RPCFuture userFuture = client.call("getUserInfo", "World");
        UserInfo result3 = (UserInfo) userFuture.get();
        System.out.println(result3.toString());
        try {
            UserInfo result2 = (UserInfo) userFuture.get(3000, TimeUnit.MILLISECONDS);
            System.out.println(result2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }

        rpcClient2.stop();
    }

}
